package com.sy.simpleegg.platform.whm.service

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.SystemClock
import android.util.Log

class TimingService : Service() {
    private val TAG = TimingService::class.java.simpleName
    private val TIME_INTERVAL = 1000 * 60 * 1 //设置三分钟执行一次
    private var mPendingIntent: PendingIntent? = null
    private var mAlarmManager: AlarmManager? = null
    override fun onCreate() {
        super.onCreate()
        val intentFilter = IntentFilter(TEST_ACTION)
        registerReceiver(receiver, intentFilter)
        mAlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
        val intent = Intent()
        intent.setAction(TEST_ACTION)
        mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //6.0低电量模式需要使用该方法触发定时任务
            mAlarmManager!!.setExactAndAllowWhileIdle(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(),
                mPendingIntent!!
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //4.4以上 需要使用该方法精确执行时间
            mAlarmManager!!.setExact(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(),
                mPendingIntent!!
            )
        } else { //4.4一下 使用老方法
            mAlarmManager!!.setRepeating(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(),
                TIME_INTERVAL.toLong(),
                mPendingIntent!!
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (TEST_ACTION == action) {
                Log.i(TAG, "定时任务执行")
                sendReadStatusOrder()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mAlarmManager!!.setExactAndAllowWhileIdle(
                        AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime() + TIME_INTERVAL,
                        mPendingIntent!!
                    )
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mAlarmManager!!.setExact(
                        AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime() + TIME_INTERVAL,
                        mPendingIntent!!
                    )
                }
            }
        }
    }

    /**
     * 发送指令读取
     */
    fun sendReadStatusOrder() {
        try {
            for (i in 3..10) {
                val timeNumber = 1000 * (i - 3)
                val msg = Message()
                msg.what = 0
                msg.obj = "指令"
                sendHandler.sendMessageDelayed(msg, timeNumber.toLong())
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, Log.getStackTraceString(e))
        }
    }

    var sendHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            val result = msg.obj.toString()
            Log.i(TAG, "Handler result: $result")
        }
    }

    companion object {
        const val TEST_ACTION = "timinService"
        fun startService(mContext: Context) {
            mContext.startService(Intent(mContext, TimingService::class.java))
        }
    }
}